package com.wsoft.hr.pm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsoft.constant.redis.HrPmRedisKeyConstant;
import com.wsoft.constant.redis.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.RedisService;
import com.wsoft.core.utils.LoginUserUtil;
import com.wsoft.entity.BaseEntity;
import com.wsoft.hr.pm.entity.*;
import com.wsoft.hr.pm.enums.TargetTypeEnum;
import com.wsoft.hr.pm.enums.TemplateStatusEnum;
import com.wsoft.hr.pm.manager.*;
import com.wsoft.hr.pm.mapper.HrPmTemplateMapper;
import com.wsoft.hr.pm.query.template.TemplateListQuery;
import com.wsoft.hr.pm.query.template.TemplateSaveQuery;
import com.wsoft.hr.pm.query.template.TemplateStateQuery;
import com.wsoft.hr.pm.query.template.scope.TemplateScopeBaseQuery;
import com.wsoft.hr.pm.query.template.scope.TemplateScopeUpdateQuery;
import com.wsoft.hr.pm.query.template.target.his.TemplateTargetHisBaseQuery;
import com.wsoft.hr.pm.query.template.target.his.TemplateTargetHisUpdateQuery;
import com.wsoft.hr.pm.service.IHrPmTemplateService;
import com.wsoft.hr.pm.vo.template.TemplateVO;
import com.wsoft.hr.pm.vo.template.scope.TemplateScopeVO;
import com.wsoft.hr.pm.vo.template.target.his.TemplateTargetHisVO;
import org.springframework.security.concurrent.DelegatingSecurityContextExecutorService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * <p>
 * 考评 模板表 服务实现类
 * </p>
 *
 * @author Z001
 * @since 2025年02月24日 18:25:38
 */
@Service
public class HrPmTemplateServiceImpl extends ServiceImpl<HrPmTemplateMapper, HrPmTemplateEntity> implements IHrPmTemplateService {

    @Resource
    private HrPmTemplateManager hrPmTemplateManager;
    @Resource
    private HrPmTemplateScopeManager templateScopeManager;
    @Resource
    private HrPmTemplateTargetManager templateTargetManager;
    @Resource
    private HrPmTemplateTargetHisManager templateTargetHisManager;
    @Resource
    private HrPmTargetManager targetManager;
    @Resource
    private HrPmProcessTemplateManager processTemplateManager;
    @Resource
    private RedisService redisService;


    /**
     * 暂存模板
     *
     * @param query
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long tempInsert(TemplateSaveQuery query,boolean isCopy) {
        //暂存不校验
        Long l = handleSave(query, TemplateStatusEnum.DRAFT.getType(), isCopy);
        removeTemplateRedisInfo(query.getId());
        return l;
    }


    /**
     * 保存模版
     *
     * @param query
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(TemplateSaveQuery query) {
        //校验 权重等数据
        checkTemplate(query);
        Long l = handleSave(query, TemplateStatusEnum.NOT_ENABLE.getType(), false);
        //移除缓存
        removeTemplateRedisInfo(query.getId());
        return l;
    }

    /**
     * 修改模版状态
     *
     * @param query
     * @return
     */
    @Override
    public boolean updateState(TemplateStateQuery query) {
        if(TemplateStatusEnum.ENABLE.getType().equals(query.getState())){
            TemplateVO templateVO = getTemplateDetail(query.getId());
            //校验模版名称
            checkTemplateName(templateVO.getName(),templateVO.getId());

            TemplateSaveQuery saveQuery = JSONObject.parseObject(JSONObject.toJSONString(templateVO), TemplateSaveQuery.class);
            //校验 权重等数据
            checkTemplate(saveQuery);

        }
        HrPmTemplateEntity templateEntity = hrPmTemplateManager.getById(query.getId());
        templateEntity.setState(query.getState());
        boolean b = hrPmTemplateManager.updateById(templateEntity);
        if (b) {
            //移除缓存
            removeTemplateRedisInfo(query.getId());
        }
        return b;
    }

    /**
     * 删除模版
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long templateId) {
        //删除模板
        hrPmTemplateManager.removeById(templateId);

        //删除模版下流程
        List<HrPmTemplateScopeEntity> scopeList = templateScopeManager.getByTemplateId(templateId);
        List<Long> scopeIdList = scopeList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        templateScopeManager.removeByIds(scopeIdList);

        //删除流程及以下 指标
        removeScope(scopeIdList);


        removeTemplateRedisInfo(templateId);
        return true;
    }

    /**
     * 模版分页
     * @param query
     * @return
     */
    @Override
    public PageInfo<HrPmTemplateEntity> listTemplate(TemplateListQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<HrPmTemplateEntity> list = hrPmTemplateManager.list(query);
        return PageInfo.of(list);
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    @Override
    @GetRedisCache(type = HrPmRedisKeyConstant.TEMPLATE_DETAIL_INFO,
            expire_sec = HrPmRedisKeyConstant.EXPIRED,
            value = RedisKeyConstant.REDIS_SELF)
    public TemplateVO getTemplateDetail(Long id) {
        TemplateVO templateVO = new TemplateVO();

        //获取模版信息
        returnTemplateInfo(id,templateVO);
        //获取模版流程信息
        returnScopeInfo(templateVO);
        //获取模版流程下的指标信息
        returnTargetInfo(templateVO.getScopeList());

        return templateVO;
    }

    /**
     * 赋值模板
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean copyTemplate(Long id) {
        TemplateVO templateVO = getTemplateDetail(id);
        //拷贝模版转换
        Long newTemplateId = convertTemplate(templateVO);
        // 复制考核流程
        processTemplateManager.copyProcessTemplate(id, newTemplateId);
        return true;
    }


    // ################################## 私有方法  ##################################

    /**
     * 拷贝模版转换
     * @param templateVO
     */
    private Long convertTemplate(TemplateVO templateVO){
        String jsonString = JSONObject.toJSONString(templateVO);
        TemplateSaveQuery query = JSONObject.parseObject(jsonString, TemplateSaveQuery.class);
        query.setId(null);
        query.setName(query.getName()+"-副本");
        List<TemplateScopeUpdateQuery> scopeList = query.getScopeList();
        if(CollUtil.isNotEmpty(scopeList)){
            for (TemplateScopeUpdateQuery scopeUpdateQuery : scopeList) {
                scopeUpdateQuery.setId(null);
                List<TemplateTargetHisUpdateQuery> hisList = scopeUpdateQuery.getTemplateTargetHisList();
                if(CollUtil.isNotEmpty(hisList)){
                    for (TemplateTargetHisUpdateQuery hisUpdateQuery : hisList) {
                        hisUpdateQuery.setId(null);
                    }
                }
            }
        }
        //复制模板
        Long newTemplateId = this.tempInsert(query, true);
        return newTemplateId;
    }

    /**
     * 获取模版维度下的指标信息
     * @param scopeVOList
     */
    private void returnTargetInfo(List<TemplateScopeVO> scopeVOList){
        if(CollUtil.isEmpty(scopeVOList)){
            return;
        }
        List<Long> scopeIdList = scopeVOList.stream().map(TemplateScopeVO::getId).collect(Collectors.toList());
        //获取维度下的所有指标
        List<HrPmTemplateTargetEntity> templateTargetList = templateTargetManager.getByScopeIds(scopeIdList);
        if(CollUtil.isEmpty(templateTargetList)){
            return;
        }
        //key:维度id,value:维度下的指标list
        Map<Long, List<HrPmTemplateTargetEntity>> targetMap = templateTargetList.stream().collect(Collectors.groupingBy(HrPmTemplateTargetEntity::getScopeId));
        //所有指标id集合
        List<Long> templateTargetIdList = templateTargetList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        List<HrPmTemplateTargetHisEntity> hisList = templateTargetHisManager.getByTemplateTargetId(templateTargetIdList);

        for (TemplateScopeVO scopeVO : scopeVOList) {
            List<HrPmTemplateTargetEntity> scopeTargetList = targetMap.get(scopeVO.getId());
            if(CollUtil.isEmpty(scopeTargetList)){
                continue;
            }
            List<Long> scopeTargetIdList = scopeTargetList.stream().map(BaseEntity::getId).collect(Collectors.toList());
            //维度下的 指标历史集合
            List<HrPmTemplateTargetHisEntity> scopehisList = hisList.stream().filter(item -> scopeTargetIdList.contains(item.getTemplateTargetId())).collect(Collectors.toList());
            List<TemplateTargetHisVO> hisVOList = scopehisList.stream().map(item -> Convert.convert(TemplateTargetHisVO.class, item)).collect(Collectors.toList());

            //判断能否修改权重==> 部门指标 默认有权重则不能修改,没有权重或者为0 则可以修改
            List<Long> targetIdList = hisVOList.stream().map(TemplateTargetHisVO::getTargetId).collect(Collectors.toList());
            if(CollUtil.isEmpty(targetIdList)){
                scopeVO.setTemplateTargetHisList(hisVOList);
            }else{
                List<HrPmTargetEntity> targetList = targetManager.listByIds(targetIdList);
                Map<Long, HrPmTargetEntity> orgTarMap = targetList.stream().collect(Collectors.toMap(HrPmTargetEntity::getId, item -> item));
                for (TemplateTargetHisVO templateTargetHisVO : hisVOList) {
                    HrPmTargetEntity targetEntity = orgTarMap.get(templateTargetHisVO.getTargetId());
                    if(null == targetEntity){
                        templateTargetHisVO.setUpdateWeight(true);
                        templateTargetHisVO.setUpdateStandard(true);
                        templateTargetHisVO.setUpdateParTargetId(true);
                        templateTargetHisVO.setUpdateRemark(true);
                        templateTargetHisVO.setUpdateGroupId(true);
                    }else{
                        if(null != targetEntity.getMemberId()){
                            //用户指标 允许编辑
                            templateTargetHisVO.setUpdateWeight(true);
                            templateTargetHisVO.setUpdateStandard(true);
                            templateTargetHisVO.setUpdateParTargetId(true);
                            templateTargetHisVO.setUpdateRemark(true);
                            templateTargetHisVO.setUpdateGroupId(true);
                        }else {
                            canUpdate(targetEntity, templateTargetHisVO);
                        }
                    }

                }
                scopeVO.setTemplateTargetHisList(hisVOList);
            }
        }

    }




    /**
     * 返回模版维度信息
     * @param templateVO
     */
    private void returnScopeInfo(TemplateVO templateVO){

        List<TemplateScopeVO> scopeVOList = new ArrayList<>();

        //获取模版下的流程
        List<HrPmTemplateScopeEntity> scopeList = templateScopeManager.getByTemplateId(templateVO.getId());
        if(CollUtil.isEmpty(scopeList)){
            templateVO.setScopeList(scopeVOList);
            return;
        }
        for (HrPmTemplateScopeEntity scope : scopeList) {
            TemplateScopeVO scopeVO = Convert.convert(TemplateScopeVO.class, scope);
            scopeVOList.add(scopeVO);
        }
        templateVO.setScopeList(scopeVOList);
    }

    /**
     * 返回模版信息
     * @param id
     * @param templateVO
     */
    private void returnTemplateInfo(Long id,TemplateVO templateVO){
        //获取模版信息
        HrPmTemplateEntity templateEntity = hrPmTemplateManager.getById(id);
        if(null == templateEntity){
            return;
        }
        templateVO.setId(templateEntity.getId());
        templateVO.setName(templateEntity.getName());
        templateVO.setCode(templateEntity.getCode());
    }


    /**
     * 删除流程及以下 指标
     * @param scopeIdList
     */
    private void removeScope(List<Long> scopeIdList){
        if(CollUtil.isEmpty(scopeIdList)){
            return;
        }
        //流程下的指标
        List<HrPmTemplateTargetEntity>  templateTargetList =  templateTargetManager.getByScopeIds(scopeIdList);

        //删除流程
        templateScopeManager.removeByIds(scopeIdList);

        if(CollUtil.isEmpty(templateTargetList)){
            return;
        }
        List<Long> targetList = templateTargetList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        if(CollUtil.isNotEmpty(targetList)){
            templateTargetManager.removeByIds(targetList);
        }

        //指标历史
        List<Long> hisIdList = templateTargetList.stream().map(HrPmTemplateTargetEntity::getTemplateTargetHisId).collect(Collectors.toList());
        if(CollUtil.isNotEmpty(hisIdList)){
            templateTargetHisManager.removeByIds(hisIdList);
        }
    }

    /**
     * 删除 指标历史表id
     * @param targetHisIdList
     */
    private void removeTargetHis(List<Long> targetHisIdList){
        if(CollUtil.isEmpty(targetHisIdList)){
            return;
        }
        List<HrPmTemplateTargetHisEntity> list = templateTargetHisManager.listByIds(targetHisIdList);
        templateTargetHisManager.removeByIds(targetHisIdList);

        List<Long> targetIdList = list.stream().map(HrPmTemplateTargetHisEntity::getTemplateTargetId).collect(Collectors.toList());
        if(CollUtil.isEmpty(targetIdList)){
            return;
        }
        if(CollUtil.isNotEmpty(targetIdList)){
            templateTargetManager.removeByIds(targetIdList);
        }
    }

    /**
     * 校验模版名称
     * @param templateName
     * @param id
     */
    private void checkTemplateName(String templateName,Long id){
        HrPmTemplateEntity enableTemplateName = hrPmTemplateManager.getEnableTemplateName(templateName);
        if(null != enableTemplateName && !enableTemplateName.getId().equals(id)){
            Asserts.fail("[hr.pm.template.name.exist]");
        }
    }

    /***
     * 模板保存校验
     * @param query
     */
    private void checkTemplate(TemplateSaveQuery query) {
        List<TemplateScopeUpdateQuery> scopeList = query.getScopeList();
        if(CollUtil.isEmpty(scopeList)){
            Asserts.fail("[hr.pm.weight.error]");
        }

        //判断维度是否有重复
        if(!isScopeIdUnique(scopeList)){
            Asserts.fail("[hr.pm.scope.repeat]");
        }

        //判断指标是否有重复
        if(!isTargetIdUnique(scopeList)){
            Asserts.fail("[hr.pm.target.repeat]");
        }


        BigDecimal scopeWeightAdd = scopeList.stream().map(TemplateScopeBaseQuery::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
        //校验维度权重是否等于100
        checkWeight(scopeWeightAdd, BigDecimal.valueOf(100),false);

        //遍历判断 指标权重之和 是否等于维度权重
        for (TemplateScopeUpdateQuery scope : scopeList) {
            List<TemplateTargetHisUpdateQuery> hisList = scope.getTemplateTargetHisList();
            if(CollUtil.isEmpty(hisList)){
                continue;
            }
            BigDecimal targetWeightAdd = hisList.stream()
                    //指标计算权重 不算 加减分项
                    .filter(item -> TargetTypeEnum.REFERENCE.getType().equals(item.getTargetType()))
                    .filter(item -> null != item.getWeight())
                    .map(TemplateTargetHisBaseQuery::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);

            checkWeight(targetWeightAdd, scope.getWeight(),true);
        }

    }



    /**
     * 使用 Stream 检查 List 中的 targetId 是否重复
     *
     * @param list 包含 TemplateTargetHisBaseQuery 对象的 List
     * @return 如果 targetId 没有重复，返回 true；否则返回 false
     */
    private boolean isTargetIdUnique(List<TemplateScopeUpdateQuery> list){
        if (list == null || list.isEmpty()) {
            // 空列表或不包含元素，视为没有重复
            return true;
        }

        //获取所有维度中的指标
        List<TemplateTargetHisUpdateQuery> targetHisList = new ArrayList<>();
        for (TemplateScopeUpdateQuery updateQuery : list) {
            List<TemplateTargetHisUpdateQuery> hisList = updateQuery.getTemplateTargetHisList();
            if(CollUtil.isNotEmpty(hisList)){
                targetHisList.addAll(hisList);
            }
        }
        //顺便校验 指标为系统计算的,必填目标值
        long count = targetHisList.stream().filter(item -> null != item.getIsFormula() && item.getIsFormula() == 1 && null == item.getPurposeValue()).count();
        if(count > 0){
            Asserts.fail("[hr.pm.purposeValue.error]");
        }


        long distinctCount = targetHisList.stream()
                // 过滤掉 null 对象和 null scopeId
                .filter(item -> item != null && item.getTargetId() != null)
                // 提取 scopeId
                .map(TemplateTargetHisBaseQuery::getTargetId)
                .distinct() // 去重
                .count(); // 计算去重后的数量

        long totalCount = targetHisList.stream()
                .filter(item -> item != null && item.getTargetId() != null)
                .count(); // 计算过滤后的总数
        // 如果去重后的数量等于总数，说明没有重复
        return distinctCount == totalCount;
    }


    /**
     * 使用 Stream 检查 List 中的 scopeId 是否重复
     *
     * @param list 包含 TemplateScopeBaseQuery 对象的 List
     * @return 如果 scopeId 没有重复，返回 true；否则返回 false
     */
    private boolean isScopeIdUnique(List<TemplateScopeUpdateQuery> list) {
        if (list == null || list.isEmpty()) {
            // 空列表或不包含元素，视为没有重复
            return true;
        }
        long distinctCount = list.stream()
                // 过滤掉 null 对象和 null scopeId
                .filter(item -> item != null && item.getScopeId() != null)
                // 提取 scopeId
                .map(TemplateScopeBaseQuery::getScopeId)
                .distinct() // 去重
                .count(); // 计算去重后的数量

        long totalCount = list.stream()
                .filter(item -> item != null && item.getScopeId() != null)
                .count(); // 计算过滤后的总数
        // 如果去重后的数量等于总数，说明没有重复
        return distinctCount == totalCount;
    }


    /**
     * 校验权重
     *
     * @param weight
     * @param standard
     */
    private void checkWeight(BigDecimal weight, BigDecimal standard,boolean canSmall) {
        if(canSmall){
            //是否可以比标准值小
            if (weight.compareTo(standard) > 0) {
                Asserts.fail("[hr.pm.weight.error]");
            }
        }else{
            if (weight.compareTo(standard) != 0) {
                Asserts.fail("[hr.pm.weight.error]");
            }
        }

    }


    /**
     * 处理保存方法
     *
     * @param query
     */
    private Long handleSave(TemplateSaveQuery query, Integer templateStatus,boolean isCopy) {
        //处理template表
        Long templateId = handleTemplate(query, templateStatus);
        //处理模板流程表
        handleTemplateScope(query.getScopeList());
//        //处理模版指标和模版指标历史表
//        for (TemplateScopeUpdateQuery updateQuery : query.getScopeList()) {
//            handleTemplateTargetHis(updateQuery.getTemplateTargetHisList(),isCopy);
//        }
//        // 使用线程池
        ExecutorService executorService = new DelegatingSecurityContextExecutorService(Executors.newFixedThreadPool(10));
        List<TemplateScopeUpdateQuery> scopeList = query.getScopeList();
        CompletableFuture<?>[] futures = new CompletableFuture[scopeList.size()];

        // 提交任务到线程池
        for (int i = 0; i < scopeList.size(); i++) {
            TemplateScopeUpdateQuery updateQuery = scopeList.get(i);
            futures[i] = CompletableFuture.runAsync(() -> {
                handleTemplateTargetHis(updateQuery.getTemplateTargetHisList(), isCopy);
            }, executorService);
        }

        //移除指标表
        if(CollUtil.isNotEmpty(query.getRemoveTargetList())){
            removeTargetHis(query.getRemoveTargetList());
        }

        //移除流程
        if(CollUtil.isNotEmpty(query.getRemoveScopeList())){
            removeScope(query.getRemoveScopeList());
        }

        // 等待所有任务完成
        CompletableFuture.allOf(futures).join();
        // 关闭线程池
        executorService.shutdown();
        return templateId;

    }

    /**
     * 处理template表
     *
     * @param query
     */
    private Long handleTemplate(TemplateSaveQuery query, Integer templateStatus) {
        //新增或修改
        HrPmTemplateEntity templateEntity = Convert.convert(HrPmTemplateEntity.class, query);
        templateEntity.setState(templateStatus);
        templateEntity.setHrOrgId(LoginUserUtil.getUserInfo().getHrOrgId());
        hrPmTemplateManager.saveOrUpdate(templateEntity);
        Long templateId = templateEntity.getId();

        //赋值模板id
        for (TemplateScopeUpdateQuery item : query.getScopeList()) {
            item.setTemplateId(templateId);
        }
        return templateId;
    }


    /**
     * 处理模板流程表
     *
     * @param scopeList
     */
    private void handleTemplateScope(List<TemplateScopeUpdateQuery> scopeList) {

        for (TemplateScopeUpdateQuery item : scopeList) {
            //新增或修改
            HrPmTemplateScopeEntity templateScopeEntity = Convert.convert(HrPmTemplateScopeEntity.class, item);
            templateScopeManager.saveOrUpdate(templateScopeEntity);

            if(CollUtil.isNotEmpty(item.getTemplateTargetHisList())){
                //赋值模板id
                for (TemplateTargetHisUpdateQuery targetHis : item.getTemplateTargetHisList()) {
                    targetHis.setTemplateScopeId(templateScopeEntity.getId());
                }
            }
        }
    }

    /**
     * 处理模版指标表 和模版指标历史表
     *
     * @param targetHisList
     */
    private void handleTemplateTargetHis(List<TemplateTargetHisUpdateQuery> targetHisList,boolean isCopy) {
        if(CollUtil.isEmpty(targetHisList)){
            return;
        }
        for (TemplateTargetHisUpdateQuery item : targetHisList) {
            handleTemplateTargetHisItem(item,isCopy);
        }
    }

    /**
     * 处理模版指标表 和模版指标历史表
     *
     * @param targetHisList
     */
    private void handleTemplateTargetHisItem(TemplateTargetHisUpdateQuery item,boolean isCopy){
        Long targetId = item.getTargetId();
        HrPmTargetEntity entity = targetManager.getById(targetId);
        if(null == entity ||  0 == entity.getEnableFlag() || null == entity.getStatus() ||  2 != entity.getStatus()){
            Asserts.fail("[hr.pm.temp.target.error]");
        }
        HrPmTemplateTargetHisEntity hisEntity = Convert.convert(HrPmTemplateTargetHisEntity.class, entity);
        hisEntity.setId(item.getId());
        hisEntity.setWeight(item.getWeight());
        hisEntity.setPurposeValue(item.getPurposeValue());
        //赋值 his表的targetId
        hisEntity.setTargetId(targetId);
        if(isCopy){
            hisEntity.setTemplateTargetId(null);
        }
        //新增或修改
        templateTargetHisManager.saveOrUpdate(hisEntity);

        HrPmTemplateTargetEntity hisId = templateTargetManager.getTemplateTargetHisId(hisEntity.getId());

        HrPmTemplateTargetEntity templateTargetEntity = new HrPmTemplateTargetEntity();
        templateTargetEntity.setId(null == hisId? null: hisId.getId());
        templateTargetEntity.setTemplateTargetHisId(hisEntity.getId());
        templateTargetEntity.setScopeId(item.getTemplateScopeId());
        templateTargetEntity.setWeight(item.getWeight());
        templateTargetEntity.setPurposeValue(item.getPurposeValue());
        templateTargetEntity.setSort(item.getSort());
        templateTargetManager.saveOrUpdate(templateTargetEntity);

        //新增的指标 需要在his标中赋值templateTargetId
        if (null == hisEntity.getTemplateTargetId()) {
            hisEntity.setTemplateTargetId(templateTargetEntity.getId());
            templateTargetHisManager.updateById(hisEntity);
        }
    }

    /**
     * 移除模版缓存
     * @param id
     */
    private void removeTemplateRedisInfo(Long id){
        if(null != id){
            redisService.del(HrPmRedisKeyConstant.TEMPLATE_DETAIL_INFO + id);
        }
    }


    /**
     * 判断指标五大参数 是否可以编辑
     * @param targetEntity
     * @param templateTargetHisVO
     */
    private void canUpdate(HrPmTargetEntity targetEntity, TemplateTargetHisVO templateTargetHisVO){
        //权重
        if (null == targetEntity.getWeight() || targetEntity.getWeight().compareTo(BigDecimal.ZERO) == 0) {
            //部门指标 权重为空或者为0 则可以编辑
            templateTargetHisVO.setUpdateWeight(true);
        } else {
            templateTargetHisVO.setUpdateWeight(false);
        }
        //标准
        if(StrUtil.isBlank(targetEntity.getStandard())){
            templateTargetHisVO.setUpdateStandard(true);
        }else{
            templateTargetHisVO.setUpdateStandard(false);
        }

        if(null == targetEntity.getPTargetId()){
            //上级指标为空则可以编辑
            templateTargetHisVO.setUpdateParTargetId(true);
        }else{
            templateTargetHisVO.setUpdateParTargetId(false);
        }

        if(null == targetEntity.getGroupId()){
            //分组为空则可以编辑
            templateTargetHisVO.setUpdateGroupId(true);
        }else{
            templateTargetHisVO.setUpdateGroupId(false);
        }

        if(null == targetEntity.getRemark()){
            //备注为空则可以编辑
            templateTargetHisVO.setUpdateRemark(true);
        }else{
            templateTargetHisVO.setUpdateRemark(false);
        }
    }

}
